package com.gitee.jwds666.fs.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class IniUtils {


    public static Map<String, List<String>> ini(String path) throws IOException {
        File file = new File(path);
        return ini(file);
    }

    /**
     * 读取ini内的数据
     * @param inputStream
     * @return
     */
    public static Map<String, List<String>> ini(InputStream inputStream) throws IOException {
        Map<String,List<String>> res = new LinkedHashMap<>();
        if (inputStream == null)return res;
        inputStream.mark(0);
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            List<String> val = new ArrayList<>();
            while((line=reader.readLine()) != null){
                line = line.trim();
                if (line.indexOf("#") !=-1){
                    line = line.substring(0,line.indexOf("#")).trim();
                }
                if (line.length() == 0){
                    continue;
                }
                if (line.equals("[]")){
                    val = new ArrayList<>();
                    res.put("",val);
                } else if (line.startsWith("[")){
                    val = new ArrayList<>();
                    res.put(line.substring(1,line.length()-1),val);
                }else{
                    val.add(line);
                }
            }
        } finally {
            inputStream.reset();
        }
        return res;
    }

    public static Map<String, List<String>> ini(File file) throws IOException {
        Map<String,List<String>> res = new LinkedHashMap<>();
        if (file.exists()){
            res = ini(new FileInputStream(file));
        }
        return res;
    }

}
